package com.yswl.pri.home.vedio;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yswl.pri.R;
import com.yswl.pri.common.ToolbarActivity;
import com.yswl.pri.guide.bean.MovieBean;
import com.yswl.pri.picture.SpacesItemDecoration;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import yswl.com.klibrary.base.BaseRecyclerAdapter;
import yswl.com.klibrary.base.BaseViewHolder;
import yswl.com.klibrary.util.EmptyRecyclerView;
import yswl.com.klibrary.util.L;

/**
 * 搜索的电影列表
 */
public class MovieSearchListActivity extends ToolbarActivity {

    private static final String TAG = "MovieSearchListActivity";
    public static final String DEF_URL = "http://www.runker.online/";

    public static void JumpAct(Context context, String search) {
        Intent intent = new Intent(context, MovieSearchListActivity.class);
        intent.putExtra("search", search);
        context.startActivity(intent);
    }

    RefreshLayout refreshLayout;
    MovieSearchListAdapter movieSearchListAdapter;
    public String key;
    public String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_search_list);
        key = getIntent().getStringExtra("search");
        title = key + " 搜索 ";
        setToolbarTitle(title);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new MyAsyncTask().execute(key);
            }
        });
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.requestFocus();
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        SpacesItemDecoration decoration = new SpacesItemDecoration(5);
        recyclerView.addItemDecoration(decoration);
        movieSearchListAdapter = new MovieSearchListAdapter(this, null, R.layout.activity_movie_search_list_item);
        EmptyRecyclerView emptyView = new EmptyRecyclerView(this);
        emptyView.setNoticeAndIcon("没有找到哟", "无影片资源嘞", -1);
        movieSearchListAdapter.setEmptyView(emptyView);
        recyclerView.setAdapter(movieSearchListAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.autoRefresh();
    }


    class MyAsyncTask extends AsyncTask<String, Void, List<MovieBean>> {
        //        String URL = "http://vip.runker.net/list/?mode=search&k=";
        // http://www.runker.online/seacher.php?wd=%E7%88%B1%E4%BA%BA
        String URL = "http://www.runker.online/seacher.php?wd=";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<MovieBean> doInBackground(String... strings) {
            String url = URL + strings[0];
            try {
                Document document = Jsoup.connect(url).header("Accept-Encoding", "gzip, deflate")
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0")
                        .maxBodySize(0).get();
                Element e = document.body();
                if (e == null) return null;
                Elements imgs = e.select(".stui-vodlist__thumb");
                if (imgs == null || imgs.size() == 0) return null;

//                Elements videoName = document.select(".activeclearfix detail");
                List<MovieBean> movies = new ArrayList<>();
                for (int i = 0; i < imgs.size(); i++) {
                    MovieBean movie = new MovieBean();
                    String imgUrl = imgs.get(i).attr("data-original");
                    String name = imgs.get(i).attr("title");
                    String urll = imgs.get(i).attr("href");
                    movie.img = imgUrl;
                    movie.name = name;
                    movie.url = urll;
                    movies.add(movie);
                    L.e(TAG, " img toString: " + imgUrl);//获取src的绝对路径
                    L.e(TAG, " sourVideos text: " + name);
                    L.e(TAG, " sourVideos href: " + urll);//获取src的绝对路径

                }
                return movies;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<MovieBean> lists) {
            super.onPostExecute(lists);
            refreshLayout.finishRefresh();
            if (lists != null && lists.size() > 0) {
                movieSearchListAdapter.setList(lists);
            }
        }
    }

    public class MovieSearchListAdapter extends BaseRecyclerAdapter<MovieBean> {

        public MovieSearchListAdapter(Context mContext, List<MovieBean> mList, int itemLayoutId) {
            super(mContext, mList, itemLayoutId);
        }

        @Override
        public void onBind(BaseViewHolder holder, final MovieBean imag, final int position) {
            ImageView imageView = holder.findById(R.id.img);
            final TextView textView = holder.findById(R.id.name);
            Glide.with(mWeakContext.get()).load(imag.img).apply(new RequestOptions().circleCrop()).into(imageView);
            textView.setText(imag.name);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String url = imag.url;
                    if (!imag.url.startsWith("http")) {
                        if (imag.url.startsWith("/")) {
                            url = DEF_URL + imag.url;
                        } else if (imag.url.startsWith(".")) {
                            url = loseHZ(imag.url);
                            url = DEF_URL + url;
                        }
                    }
                    MoviePageListActivity.JumpAct(v.getContext(), url, key);
                }
            });
        }
    }

    public static String loseHZ(String uri) {
        String urii = uri;
        if (urii.startsWith("./")) {
            urii = urii.substring(2);
            urii = loseHZ(urii);
        }
        if (urii.startsWith("../")) {
            urii = urii.substring(3);
            urii = loseHZ(urii);
        }
        return urii;
    }

    public static void main(String[] args) {
        String uu = "../.././aaaa";
        uu = "./cxplay/15707.html";
        uu = loseHZ(uu);
        System.out.println(uu);
    }
}
